<template>
	<view class="content">
		<u-loading-page :loading="loading" loading-text="Loading..."></u-loading-page>
		<view v-if="!loading">
			<view class="index_banner">
				<view class="" style="padding: 10px 30px;box-sizing:border-box;font-size:20px; color: #fff">
					Hi, {{ userInfo.nickname }}
					<view style="font-size: 14px; color: #fff; margin-top: 10px; opacity: 0.9;">
						您可在这里修改头像或个人信息
					</view>
				</view>
			</view>
			<!-- <view style="width: 100%;">
				<u-notice-bar text="为确保信息安全, 我们仅支持使用微信昵称, 暂不支持自定义! "></u-notice-bar>
			</view> -->
			<view style="box-sizing: border-box;font-size: 14px;color: #333;">
				<view class="item-list">
					<!-- <view class="item-list-item">
						<view>
							<text style="font-weight: bold;margin-right: 10px;width: 80px;font-size:16px">个人资料</text>
						</view>
						<view></view>
					</view> -->
					<view class="item-list-item"
						style="justify-content: center;margin-bottom: 20px;border: 0;background: unset;">
						<button
							style="border:unset;border-radius:100%;width:80px;height: 80px;display:flex;align-items:center;justify-content:center;"
							open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
							<u-avatar :src="userInfo.avatarUrl" size="80"></u-avatar>
						</button>
					</view>
					<view class="item-list-item">
						<view>
							<text style="font-weight: bold;margin-right: 10px;">昵称: </text>
						</view>
						<view style="display: flex;align-items: center;">
							<input @blur="nicknameChange" @input="nicknameChange" type="nickname"
								style="text-align:right;border-bottom:1px solid #ccc;border-radius: 0;"
								:value="userInfo.nickname" />
						</view>
					</view>
					<!-- 新增性别选择 -->
					 <view class="item-list-item">
					    <view>
					      <text style="font-weight: bold; margin-right: 10px;">性别: </text>
					    </view>
					    <view style="display: flex; align-items: center;">
					      <radio-group @change="genderChange" :value="userInfo.gender">
					        <label style="margin-right: 20px;">
					        	<radio value="1" :checked="userInfo.gender == 1" /> 男
					        </label>
					        <label>
					        	<radio value="2" :checked="userInfo.gender == 2" /> 女
					        </label>
					      </radio-group>
					    </view>
					  </view>
				 	<view class="item-list-item">
						<view>
							<text style="font-weight: bold;margin-right: 10px;">出生年月: </text>
						</view>
						<view style="display: flex;align-items: center;">
							<picker 
								mode="date" 
								fields="month"
								:value="birthDate"
								:start="startDate"
								:end="endDate"
								@change="bindBirthDateChange"
								class="birth-picker"
							>
								<view class="picker-display">
									<text style="text-align:right;color: #333;">{{ birthDateDisplay }}</text>
									<u-icon name="arrow-down" size="14" color="#999" style="margin-left: 5px;"></u-icon>
								</view>
							</picker>
						</view>
					</view>
<!--					<view class="item-list-item">-->
<!--						<view>-->
<!--							<text style="font-weight: bold;margin-right: 10px;">唯一账号: </text>-->
<!--						</view>-->
<!--						<view style="display: flex;align-items: center;">-->
<!--							<text>{{ userInfo.username }}</text>-->
<!--						</view>-->
<!--					</view>-->
<!--					<view class="item-list-item">-->
<!--						<view>-->
<!--							<text style="font-weight: bold;margin-right: 10px;">手机号码: </text>-->
<!--						</view>-->
<!--						<view style="display: flex;align-items: center;">-->
<!--							<text>{{ userInfo.mobile }}</text>-->

<!--						</view>-->
<!--					</view>-->
<!--					<view class="item-list-item">-->
<!--						<view>-->
<!--							<text style="font-weight: bold;margin-right: 10px;">个性签名: </text>-->
<!--						</view>-->
<!--						<view style="display: flex;align-items: center;">-->
<!--                            <input @blur="nicknameChange" @input="nicknameChange" type="nickname"-->
<!--                                   style="text-align:right;border-bottom:1px solid #ccc;border-radius: 0;"-->
<!--                                   :value="userInfo.nickname" />-->
<!--&lt;!&ndash;							<picker mode="date" :value="userInfo.birthday"&ndash;&gt;-->
<!--&lt;!&ndash;								@change="bindDateChange">&ndash;&gt;-->
<!--&lt;!&ndash;								<view class="uni-input">{{userInfo.birthday}}</view>&ndash;&gt;-->
<!--&lt;!&ndash;							</picker>&ndash;&gt;-->
<!--						</view>-->
<!--					</view>-->
<!--					<view class="item-list-item">-->
<!--						<view>-->
<!--							<text style="font-weight: bold;margin-right: 10px;">注册时间</text>-->
<!--						</view>-->
<!--						<view style="display: flex;align-items: center;">-->
<!--							<text>{{  userInfo.registerTime }} </text>-->

<!--						</view>-->
<!--					</view>-->
					<!-- <view class="item-list-item">
						<view>
							<text style="font-weight: bold;margin-right: 10px;">客服微信: </text>
						</view>
						<view style="display: flex;align-items: center;">
							<text>{{  userInfo.customer==null?'':userInfo.customer }} </text>
						</view>
					</view> -->
				</view>
				<!-- <view class="item-list">
					<view class="item-list-item">
						<view>
							<text style="font-weight: bold;margin-right: 10px;width: 80px;font-size:16px">短信通知</text>
						</view>
						<view></view>
					</view>
					<view class="item-list-item">
						<view>
							<span style="font-size: 12px;">
								为了确保您的资金安全和及时收到我们的最新活动信息，我们将为您提供以下消息的定向短信推送，如您不需要短信推送，您可随时在此关闭，关闭后我们将不再为您推送短信通知
							</span>
						</view>
					</view>
					<view class="item-list-item">
						<view style="display:flex;align-items:center;justify-content: space-between;width: 100%;">
							<view>
								<text style="font-weight: bold;margin-right: 10px;">消费通知</text>
								<text style="font-weight: 400;margin-right: 10px;color: #777;font-size: 12px;">(结账后推送消费金额等)</text>
							</view>
							<view style="display:flex;align-items:center;">
								<u-switch :size="16" v-model="userInfo.is_sms_consume"></u-switch>
							</view>
						</view>
					</view>
					<view class="item-list-item">
						<view style="display:flex;align-items:center;justify-content: space-between;width: 100%;">
							<view>
								<text style="font-weight: bold;margin-right: 10px;">余额通知</text>
								<text style="font-weight: 400;margin-right: 10px;color: #777;font-size: 12px;">(推送余额变动及返现通知)</text>
							</view>
							<view style="display:flex;align-items:center;">
								<u-switch :size="16" v-model="userInfo.is_sms_money"></u-switch>
							</view>
						</view>
					</view>
					<view class="item-list-item">
						<view style="display:flex;align-items:center;justify-content: space-between;width: 100%;">
							<view>
								<text style="font-weight: bold;margin-right: 10px;">活动通知</text>
								<text style="font-weight: 400;margin-right: 10px;color: #777;font-size: 12px;">(推送最新活动或营销信息)</text>
							</view>
							<view style="display:flex;align-items:center;">
								<u-switch :size="16" v-model="userInfo.is_sms_active"></u-switch>
							</view>
						</view>
					</view>
				</view> -->
			</view>
			
			<view class="item-list-item" style="justify-content: center;margin-top: 50rpx;">
				<view @click="setUserInfo">
					<u-button :customStyle="{width:'200px'}" type="success" text="确认保存"
						style="width: 100%;"></u-button>
				</view>
			</view>
			<view style="margin-top: 50px;padding-bottom: 30px;">
				<view style="display: flex; justify-content: center; align-items: center;">
					<image 
						src="http://xaiohua.oss-cn-beijing.aliyuncs.com/medias/trees/treeId/images/fc1d61d4-16ad-4489-97e0-31e3fd16fff9.jpg?Expires=4911628274&OSSAccessKeyId=LTAI5t93GNuNHEtLjPm4NWTG&Signature=DIEiLHKgHSs4F0OUWE2fDZRwOpk%3D"
						mode="aspectFit"
						style="width: 1500rpx; height: 450rpx;"
					></image>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import ali_oss_upload from '@/common/ossutil/uploadFile.js';
	export default {
		data() {
			return {
				userInfo: {
					nickname: '游客',
                    avatarUrl: '游客',
					gender:1,
					age:18,
					birthDate: '' // 添加出生日期字段
				},
				loading: true,
				status: 'all',
				uploadOssClient:null,
				// 出生年月选择器相关
				birthDate: '',
				startDate: '1950-01', // 最早年份
				endDate: '' // 当前年月，在 onLoad 中设置
			}
		},
		computed: {
			// 显示出生年月的文本
			birthDateDisplay() {
				// 优先使用 birthDate 字段
				if (this.birthDate) {
					return this.birthDate.replace('-', '年') + '月';
				}
				// 如果没有 birthDate 但有 userInfo.birthDate
				if (this.userInfo.birthDate) {
					return this.userInfo.birthDate.replace('-', '年') + '月';
				}
				// 都没有的情况下，显示默认文本
				return '请选择出生年月';
			}
		},
		async onLoad(e) {
			// await this.$getUploadConfig()
			// ali_oss_upload.setConfig(this.$uploadConfig)
			
			// 设置当前日期为最大可选择日期
			const now = new Date();
			const year = now.getFullYear();
			const month = String(now.getMonth() + 1).padStart(2, '0');
			this.endDate = `${year}-${month}`;
			
			// 检查本地存储的用户信息
			const localUserInfo = uni.getStorageSync('userInfo');
			if (localUserInfo && localUserInfo.age && localUserInfo.age > 0 && !localUserInfo.birthDate) {
				// 如果有年龄但没有出生日期，先反推出生年月
				this.calculateBirthDateFromAge(localUserInfo.age);
			}
			
		},
		methods: {
			init() {
				Promise.all([
					this.getUserInfo()
				]).then(results => {
					uni.hideLoading()
					uni.stopPullDownRefresh()
					this.loading = false
				}).catch(err => {
					uni.hideLoading()
					uni.stopPullDownRefresh()
					this.loading = false
				});
			},
			img_uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					// 阿里云OSS
					// ali_oss_upload.uploadFile(url, 'information/images/tx/',
					//     (result)=>{
					// 		resolve(result);
					// 	}
					// )
					// 本地上传
                    let a = uni.uploadFile({
                        url: this.$baseUrl + 'system/api/treeMedia/treeId/upload?mediaType=image&uploadType=upReport',
                        filePath: url,
                        name: 'file',
                        formData: {},
                        header: {
                            Authorization: uni.getStorageSync('token')
                        },
                        success: (res) => {
                            setTimeout(() => {
                                res.data = JSON.parse(res.data)
                                resolve(res.data.data)
                            }, 1000)
                        }
                    });
				})
			},
			bindDateChange(data) {
				this.userInfo.birthday = data.detail.value
			},
			nicknameChange(data) {
				this.userInfo.nickname = data.detail.value
			},
			ageChange(data) {
				this.userInfo.age = data.detail.value
			},
			// 出生年月选择改变事件
			bindBirthDateChange(e) {
				this.birthDate = e.detail.value;
				// 根据出生年月计算年龄
				this.calculateAge();
			},
			// 计算年龄
			calculateAge() {
				if (this.birthDate) {
					const [birthYear, birthMonth] = this.birthDate.split('-').map(Number);
					const now = new Date();
					const currentYear = now.getFullYear();
					const currentMonth = now.getMonth() + 1;
					
					let age = currentYear - birthYear;
					// 如果当前月份还没到生日月份，年龄减1
					if (currentMonth < birthMonth) {
						age--;
					}
					
					this.userInfo.age = age;
					// 保存出生日期到 userInfo
					this.userInfo.birthDate = this.birthDate;
				}
			},
			
			// 根据年龄反推出生年月
			calculateBirthDateFromAge(age) {
				if (age && age > 0) {
					const now = new Date();
					const currentYear = now.getFullYear();
					const currentMonth = now.getMonth() + 1;
					
					// 计算出生年份：当前年份 - 年龄
					const birthYear = currentYear - age;
					// 使用当前月份作为默认的出生月份
					const birthMonth = String(currentMonth).padStart(2, '0');
					
					// 设置出生年月
					this.birthDate = `${birthYear}-${birthMonth}`;
					// 同时更新 userInfo 中的出生日期
					this.userInfo.birthDate = this.birthDate;
					
					console.log(`根据年龄 ${age} 反推出生年月: ${this.birthDate}`);
				}
			},
			// 新增性别选择方法
			genderChange(e) {
				this.userInfo.gender = parseInt(e.detail.value)
			},
			async onChooseAvatar(val) {
				let tmpFilePath = val.detail.avatarUrl
				const result = await this.img_uploadFilePromise(tmpFilePath)
                console.log(77777,result.url)
				this.userInfo.avatarUrl = result.url
			},
			/**
			 * 用户信息
			 */
			getUserInfo(is_loading = false) {
				return new Promise((suc, err) => {
					this.$http.to_http('system/miniUser/getByToken', {}, 'GET', is_loading).then(res => {
						res = res.data
						if (res.code != 200) {
							return uni.showToast({
								title: "系统维护中",
								icon: "none"
							})
						}
						this.userInfo = res.data
						// 如果服务器返回了出生日期，设置到本地变量
						if (res.data.birthDate) {
							this.birthDate = res.data.birthDate;
						} else if (res.data.age && res.data.age > 0) {
							// 如果没有出生日期但有年龄，根据年龄反推出生年月
							this.calculateBirthDateFromAge(res.data.age);
						}
						uni.setStorageSync('userInfo', res.data)
						suc(true);
					})
				})
			},
			setUserInfo() {
				return new Promise((suc, err) => {
					this.$http.to_http('auth/wxUpdateInfo', this.userInfo, 'POST', "提交中...").then(res => {
						res = res.data
						if (res.code != 200) {
							return uni.showToast({
								title: res.msg,
								icon: "none"
							})
						}
						this.getUserInfo()
						 setTimeout(() => {
						      this.to_mine()  // 跳转到目标路由
						    }, 300) 
						return uni.showToast({
							title: "保存成功",
							icon: "none"
						})
						suc(true);
					})
				})
			},
			to_home() {
				uni.switchTab({
					url: "/pages/index/index"
				})
			},
			to_mine() {
				uni.switchTab({
					url: "/pages/my/my"
				})
			},
			to_back() {
				uni.navigateBack()
			},
			selectTabs(data) {
				this.status = data.status
				this.getOrders()
			}
		},
		onShow() {
			this.init()
		},
		onPullDownRefresh() {
			this.init()
		}
	}
</script>

<style scoped lang="scss">
	.content {
		background: #f6f6F6;
		min-height: 100vh;
	}

	.index_banner {
		height: 200rpx;
		width: 100%;
		background: linear-gradient(135deg, #25772f, #4CAF50);
		background-size: cover;
		background-position: center;
		padding: 15px;
		color: #fff;
		display: flex;
		align-items: center;
	}

	.item-list {
		width: 100%;
		min-height: 50px;
		background: #fff;
		padding: 15px;
		box-sizing: border-box;
		margin-bottom: 10px;
	}

	.item-list-item {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 25rpx;
	}
	
	/* 出生年月选择器样式 */
	.birth-picker {
		min-width: 160px;
	}
	
	.picker-display {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		padding: 10px 0;
		border-bottom: 1px solid #ccc;
		min-height: 20px;
		cursor: pointer;
	}
</style>